package sess

import (
	"src/zeus/iserver"
	"src/zeus/msghandler"
)

// IMsgServer 消息服务器接口
type IMsgServer interface {
	iserver.IMsgHandler
	IConnReceiver

	Start() error
	Close()
	//获取使用的端口
	GetPort() int
	// 对外的端口
	GetEtcdPort() int
	MainLoop()
	GetSession(id uint64) iserver.ISess
	SetEncryptEnabled()
	SetSessionVerifyHandler(handler ISessionVerifyHandler)
	// 遍历所有被动连接，返回false就退出遍历
	RangeSess(f func(sess iserver.ISess) bool)
}

// NewMsgServer 创建一个消息监听器
func NewMsgServer(protocal string, info iserver.PortInfo) IMsgServer {
	srv := new(MsgServer)

	mh := msghandler.NewMsgHandler()

	// srv.IMsgHandlers = mh
	srv.SessMgr = newSessMgr(mh)
	srv.INetSrv = newNetSrv(protocal, srv, info)
	// srv.listenAddr = addr
	// srv.maxConn = maxConns

	return srv
}

// MsgServer 消息服务器
type MsgServer struct {
	// iserver.IMsgHandlers
	*SessMgr
	INetSrv
	// maxConn    int
	// listenAddr string
}

func (srv *MsgServer) SetSessionVerifyHandler(handler ISessionVerifyHandler) {
	srv.SessMgr.SetVerifyHandler(handler)
}

// Start 启动服务器
func (srv *MsgServer) Start() error {
	return srv.INetSrv.start()
}

// Close 关闭服务器
func (srv *MsgServer) Close() {
	srv.SessMgr.close()
	srv.INetSrv.close()
}

// SetEncryptEnabled 是否加密
func (srv *MsgServer) SetEncryptEnabled() {
	srv.SessMgr.SetEncryptEnabled()
}

// GetSession 获取一个Sess对象
func (srv *MsgServer) GetSession(id uint64) iserver.ISess {
	return srv.SessMgr.getSessByID(id)
}

// MainLoop 每帧调用
func (srv *MsgServer) MainLoop() {
	srv.MsgHandler.DoMsg()
}
